package me.sdevil507.mobile.wxApplet.util;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRRequest;
import com.tencentcloudapi.ocr.v20181119.models.GeneralBasicOCRResponse;
import com.tencentcloudapi.ocr.v20181119.models.TextDetection;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 小程序获取必要数据工具类
 * @author: Created by Zhaoj on 2019-12-25 16:42.
 */
public class WxUtil {

    /**
     * 获取access_token
     * appid和appsecret到小程序后台获取
     * @param appid
     * @param appsecret
     * @return
     */
    public static String getAccessToken(String appid, String appsecret) {
        String  accessToken = "";
        try {
            String url = "https://api.weixin.qq.com/cgi-bin/token";
            String grantType = "client_credential";
            String tokenUrl = url + "?grant_type=" + grantType + "&appid=" + appid + "&secret=" + appsecret;
            String get = HttpClientUtil.doGet(tokenUrl);
            JSONObject jsons = JSONObject.parseObject(get);
            if(jsons != null){
                accessToken = jsons.getString("access_token");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    /**
     * 获取手机号码
     * @return
     */
    public static String getPhoneNumber(String access_token, String phoneNumber_code) {
        String phoneNumber = "";
        try {
            String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token="+ access_token;

            JSONObject requestObj = new JSONObject();
            requestObj.put("code", phoneNumber_code);

            String postStr = HttpClientUtil.doPostJson(url, requestObj.toString());
            JSONObject jsons = JSONObject.parseObject(postStr);
            System.out.println("---------获取到的手机号json---------"+jsons.toJSONString());

            phoneNumber = jsons.getJSONObject("phone_info").getString("phoneNumber");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return phoneNumber;
    }

    /**
     * 获取access_token
     * appid和appsecret到H5后台获取
     * @param appid
     * @param appsecret
     * @return
     */
    public static JSONObject getH5AccessToken(String appid, String appsecret, String code) {
        JSONObject jsons = new JSONObject();
        try {
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
            String grantType = "authorization_code";
            String tokenUrl = url + "?grant_type=" + grantType + "&appid=" + appid + "&secret=" + appsecret + "&code=" + code;
            String get = HttpClientUtil.doGet(tokenUrl);
            jsons = JSONObject.parseObject(get);
//            if(jsons != null){
//                accessToken = jsons.getString("access_token");
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsons;
    }


    public static JSONObject getH5UserInfo(Object access_token, Object openid) {
        JSONObject jsons = new JSONObject();
        try {
            String url = "https://api.weixin.qq.com/sns/userinfo";
            String infoUrl = url + "?access_token=" + access_token + "&openid=" + openid;
            String get = HttpClientUtil.doGet(infoUrl);
            jsons = JSONObject.parseObject(get);
//            if(jsons != null){
//                accessToken = jsons.getString("access_token");
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsons;
    }

    public static String recognizePrintedTextOcr(String imageUrl) {
        try{
            // 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey,此处还需注意密钥对的保密
            // 代码泄露可能会导致 SecretId 和 SecretKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议采用更安全的方式来使用密钥,请参见：https://cloud.tencent.com/document/product/1278/85305
            // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
            Credential cred = new Credential("AKIDSnzxheT4QXVJuGn8F6iFYcQ2UlodGemg", "vb2DF6k9LNBm8GAtAJExSmuxrY2JMBqI");
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("ocr.tencentcloudapi.com");
            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            OcrClient client = new OcrClient(cred, "ap-shanghai", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            GeneralBasicOCRRequest req = new GeneralBasicOCRRequest();
            req.setImageUrl(imageUrl);
            req.setScene("ap-shanghai");

            // 返回的resp是一个GeneralBasicOCRResponse的实例,与请求对象对应
            GeneralBasicOCRResponse resp = client.GeneralBasicOCR(req);
            // 输出json格式的字符串回包
            System.out.println("-------识别出的原始内容-------"+GeneralBasicOCRResponse.toJsonString(resp));

            List<String> textList = new ArrayList<>();
            for (TextDetection textDet : resp.getTextDetections()) {
                textList.add(textDet.getDetectedText());
            }
            System.out.println("-------提取出的内容-------"+textList.toString());
            return textList.toString();
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
//        String imagePath = "https://ttfruitfile.oss-cn-beijing.aliyuncs.com/fruit-prod/c1b41e5f65c846e1b283153ebb0763d1.jpg";
//        String result = recognizePrintedTextOcr(imagePath);
//        System.out.println(result);

        String result = "{\"name\": \"长江文化研究重大课题项目工作研讨会议程\",\"theme\": \"长江文化研究重大课题项目\",\"pubTime\": \"2023-04-04\",\"author\": \"徐宁,周宪,贺云翱,张鸿雁,李玉,鲁安东,周计武,李健,干有成\",\"organization\": \"省委宣传部、南京大学\",\"address\": \"西康宾馆6号楼第五会议室\",\"summary\": \"省委宣传部规划办介绍社科基金立项有关要求,省委宣传部文化产业处介绍课题研究成果要求,各课题组介绍研究计划和工作推进情况,交流讨论。\",\"keyword\": \"长江文化研究,工作研讨会议程\"}";


        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(result);

        String name = jsonNode.get("name").asText();
        String pubTime = jsonNode.get("pubTime").asText();
        // 其他字段类似

        System.out.println("Name: " + name);
        System.out.println("PubTime: " + pubTime);
    }
}
